package com.hmall.item.web;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private IItemService itemService;


    @Autowired
    private ItemMapper itemMapper;

    @GetMapping("/hi")
    public String hi() {

        //Item item = itemMapper.selectById(1L);
        //itemService.selectByID(1L);
        itemService.getById(1L);
        return "hi";
    }

    @GetMapping("/list")
    public PageDTO<Item> queryItemByPage(@RequestParam Integer page, Integer size) {
        // 分页查询
        Page<Item> itemPage =  new Page<>(page, size);
        //Page<Item> result = itemService.page(new Page<>(page, size));
        itemService.page(itemPage);
        // 封装并返回
        return new PageDTO<>(itemPage.getTotal(), itemPage.getRecords());
    }

    @GetMapping("{id}")
    public Item queryItemById(@PathVariable("id") Long id) {
        return itemService.getById(id);
    }

    @PostMapping
    public void saveItem(@RequestBody Item item) {
        // 基本数据
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        item.setStatus(2); //默认下架
        // 新增
        itemService.save(item);
    }

    @PutMapping("/status/{id}/{status}")
    public void updateItemStatus(@PathVariable("id") Long id,
                                 @PathVariable("status") Integer status){
        //update tb_item set status = ? where id = ?
        itemService.update(Wrappers.<Item>lambdaUpdate()
                .set(Item::getStatus, status)
                .eq(Item::getId, id));
    }

    @PutMapping
    public void updateItem(@RequestBody Item item) {
        // 基本数据
        item.setUpdateTime(new Date());
        // 不允许修改商品状态，所以强制设置为null，更新时，就会忽略该字段
        if (item.getStatus() != null) {
            //where status = ?
        }
        item.setStatus(null);
        // 更新
        itemService.updateById(item);
    }

    @DeleteMapping("{id}")
    public void deleteItemById(@PathVariable("id") Long id) {
        itemService.removeById(id);
    }


    @PutMapping("/stock/{itemId}/{num}")
    public void updateStock(@PathVariable("itemId") Long itemId,
                            @PathVariable("num") Integer num) {
        itemService.deductStock(itemId, num);
    }
}
